package com.tvein.sanguo.controller.Game.system
{
	//flash
	import flash.display.DisplayObject;
	import flash.display.Loader;
	import flash.utils.ByteArray;
	import flash.net.URLRequest;
	import flash.events.Event;
	import flash.utils.Timer;
	import flash.events.TimerEvent;
	//pureMVC
	import org.puremvc.as3.multicore.interfaces.ICommand;
	import org.puremvc.as3.multicore.interfaces.INotification;
	import org.puremvc.as3.multicore.utilities.fabrication.patterns.command.SimpleFabricationCommand;
	import org.puremvc.as3.multicore.utilities.fabrication.components.FlashApplication;
	//custom
	import com.tvein.sanguo.common.CommonConstants;
	import com.tvein.sanguo.view.ApplicationMediator;
	import com.tvein.sanguo.model.ServerProxy;
	import com.tvein.sanguo.model.FilesProxy;
//
	public class ModuleLoad extends SimpleFabricationCommand implements ICommand
	{
		private var sanguoMediator:ApplicationMediator;
		private var serverData:ServerProxy;
		private var filesData:FilesProxy;
		
		override public function execute(notification:INotification) : void
		{
			sanguoMediator = facade.retrieveMediator(ApplicationMediator.NAME) as ApplicationMediator;
			serverData = facade.retrieveProxy( ServerProxy.NAME ) as ServerProxy;
			filesData = facade.retrieveProxy(FilesProxy.NAME) as FilesProxy;
			
			var fileSrc:String;
			
			for (var i:int = 0; i < filesData.filesArray.length; i++)
			{
				fileSrc = filesData.filesArray[i][0].split("|")[0];
				
				if (fileSrc == notification.getBody()[1]) 
				{
					loadModule(fileSrc.substring(fileSrc.lastIndexOf("/") + 1, fileSrc.lastIndexOf(".")), filesData.filesArray[i][1]);
				}
			}
		}
		
		//Custom
		private function loadModule(moduleName:String, moduleData:ByteArray):void
		{
			var moduleLoader:Loader = new Loader();
			moduleLoader.contentLoaderInfo.addEventListener(Event.COMPLETE, function(evt:Event):void { _completeListener(evt, moduleName);} );
			
			moduleLoader.loadBytes(moduleData);
		}
		
		private function _completeListener(evt:Event, moduleName:String):void
		{
			evt.target.removeEventListener(Event.COMPLETE, _completeListener);
			
			var content:FlashApplication = FlashApplication(evt.target.content);
			content.router = sanguoMediator.applicationRouter;
			content.defaultRouteAddress = sanguoMediator.applicationAddress;
			
			sanguoMediator.sanguo.addChild(content);
			
			serverData.setSwfName(moduleName, content.name);
		}
	}
}